﻿using System;
using System.IO;
using System.Linq;
using System.Text;

namespace CloudManager.ThirdPartyProviders
{
    internal sealed class DropboxProvider : CloudService
    {

        private const string guid = "2c0ed794-6d21-4c07-9fdb-f076662715ad";

        private  static string dropboxDatabasePath;

        //Based on the Batch file downloaded here: http://social.technet.microsoft.com/Forums/da-DK/officeitpro/thread/b00bdfcc-a1d7-488a-b509-534575735839
        
        //Local folder info: http://stackoverflow.com/questions/9660280/how-do-i-programmatically-locate-my-dropbox-folder-using-c

        internal DropboxProvider()
        {
            Guid = guid;

            DisplayName = "Dropbox";
            Description = "Dropbox is a free service that lets you bring all your photos, docs, and videos anywhere.";
            InformationUrl = "https://www.dropbox.com/";
            AccountUrl = "https://www.dropbox.com/account";
            Url48x48 = "http://dl.dropbox.com/u/46565/metro/Dropbox_48x48.png";
            Url40x40 = "http://dl.dropbox.com/u/46565/metro/Dropbox_40x40.png";
            Url32x32 = "http://dl.dropbox.com/u/46565/metro/Dropbox_32x32.png";
            Url24x24 = "http://dl.dropbox.com/u/46565/metro/Dropbox_24x24.png";
            Url20x20 = "http://dl.dropbox.com/u/46565/metro/Dropbox_20x20.png";
            Url16x16 = "http://dl.dropbox.com/u/46565/metro/Dropbox_16x16.png";
            LocalFolder = GetDropboxFolder().FullName;
        }

        internal static string DropboxDatabase()
        {
            if(string.IsNullOrWhiteSpace(dropboxDatabasePath))
            {
                dropboxDatabasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Dropbox\\host.db");

                if(File.Exists(dropboxDatabasePath))
                {
                    return dropboxDatabasePath;
                }
                else
                {
                    dropboxDatabasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Dropbox\\host.db");
                }
            }

            return dropboxDatabasePath;
        }

        internal static bool IsInstalled()
        {
            var t = DropboxDatabase();

            return File.Exists(t);
        }

        internal static bool IsRegistered()
        {
            var re = new RegistryEditor();

            var keyObj = re.GetKey(BaseKey, false);

            var subKeys = keyObj.GetSubKeyNames();

            return subKeys.Contains(guid);
        }

        private DirectoryInfo GetDropboxFolder()
        {
            var dbPath = Path.Combine(DropboxDatabase());

            var dbBase64Text = Convert.FromBase64String(File.ReadAllLines(dbPath)[1]);

            return new DirectoryInfo(Encoding.ASCII.GetString(dbBase64Text));
        }

    }
}
